package org.projectback.filters.SecurityFilters;

import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.projectback.utils.ResultMessage;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Order(-101)
public class FlowLimitFilter implements Filter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String address = httpRequest.getRemoteAddr();
        if (tryBlock(address)) {
            //true
           filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //false
            writeBlockMessage(httpResponse);
        }
    }
    private void writeBlockMessage(HttpServletResponse httpResponse) throws IOException {
        httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpResponse.setContentType("application/json");
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.getWriter().write(ResultMessage.forbidden().toJsonString());
    }
    private boolean tryBlock(String address) {
        if (stringRedisTemplate.hasKey("block-ip"+address)) {
            return false;
        }else {

            return addCount(address);
        }
    }
    private boolean addCount(String address){
        if (stringRedisTemplate.hasKey("count-ip"+address)) {
            long increment = Optional.ofNullable(stringRedisTemplate.opsForValue().increment("count-ip"+address)).orElse(0L);
            if (increment >15L) {
                stringRedisTemplate.delete("count-ip"+address);
                stringRedisTemplate.opsForValue().set("block-ip"+address,"",30,TimeUnit.SECONDS);
                return false;
            }
        }else {
            stringRedisTemplate.opsForValue().set("count-ip"+address,"1",30, TimeUnit.SECONDS);
        }
        return true;
    }
}
